import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Tooltip, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormInstance, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import { getArticleColumn, updateArticleColumn, addArticleColumn } from './service';
import type { TableListItem, TableListPagination } from './data';
import { setLocale } from 'umi';

// 添加专栏
const addColumn = async (value: string) => {
  const { code } = await addArticleColumn({ column: value });
  code === 1000 ? message.success('该类型审核失败') : message.error('该类型审核失败');
};
const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  // state setState class
  // hooks useState
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  //  const [a,setA] = useState<string>('')
  // setA('ssss')
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const [visible, setVisible] = useState(false);
  const username = localStorage.getItem('username');
  const [submitParams, setSubmitParams] = useState({
    column: '',
    examine_user: username,
    user_id: '',
    examine: 2,
    result: '',
  });
  /** 国际化配置 */
  // 列的内容
  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      search: false,
      // tip: '规则名称是唯一的 key',
      render: (dom, entity) => (
        <a
          onClick={() => {
            setCurrentRow(entity);
            setShowDetail(true);
            console.log(dom, entity);
          }}
        >
          {dom}
        </a>
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      valueType: 'textarea',
      hideInForm: true,
      search: false,
    },
    {
      title: '用户id',
      dataIndex: 'user_id',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '文章专栏',
      dataIndex: 'column',
      valueType: 'textarea',
    },
    {
      title: '专栏描述',
      dataIndex: 'column_detail',
      valueType: 'textarea',
      search: false,
    },

    {
      title: '审核人员',
      dataIndex: 'examine_user',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '审核日期',
      dataIndex: 'examine_date',
      valueType: 'dateRange',
      search: {
        transform: (value: any) => ({ examine_date_from: value[0], examine_date_to: value[1] }),
      },
      render: (dom, record) => <span>{record.examine_date}</span>,
    },
    {
      title: '审核状态',
      dataIndex: 'check',
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        0: {
          text: '未审核',
          status: 'Error',
        },
        1: {
          text: '审核通过',
          status: 'Success',
        },
        2: {
          text: '审核未通过',
          status: 'Error',
        },
      },
      render: (dom, entity) => (
        <div>
          {entity?.examine == '0' ? '未审核' : entity?.examine == '1' ? '审核通过' : '审核未通过'}
        </div>
      ),
    },
    // {
    //   title: '审核失败原因',
    //   dataIndex: 'result',
    //   valueType: 'textarea',
    //   hideInForm: true,
    //   search: false,
    //   render: (dom, record) => (
    //     <div>
    //       <Tooltip placement="top" title={record?.result}>
    //         {record?.result?.length > 6 ? `${record?.result.split(0, 6)}...` : record?.result}
    //       </Tooltip>
    //     </div>
    //   ),
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            console.log('我是入参', record);
            goArticleColumn(record?.column, record?.user_id);
          }}
        >
          审核成功
        </a>,
        <a
          key="config"
          onClick={() => {
            setVisible(true);
            setSubmitParams({
              ...submitParams,
              user_id: record.user_id,
              column: record.column,
            });
          }}
        >
          审核失败
        </a>,
      ],
    },
  ];
  // 审核接口
  const goArticleColumn = async (column: any, user_id: string) => {
    const {
      res: { code },
    } = await updateArticleColumn({ column, examine_user: username, user_id, examine: 1 });
    code === 1000 ? message.success('专栏审核通过') : message.error('专栏审核失败');
  };
  // 审核接口
  const gooutArticleColumn = async () => {
    const { res: { code } } = await updateArticleColumn(submitParams);
    code === 1000 ? message.success('专栏审核通过') : message.error('专栏审核失败');
    setVisible(false)
  };
  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="专栏管理"
        scroll={{ x: 1500 }}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            {/* <PlusOutlined /> 添加 */}
          </Button>,
        ]}
        // 请求列表数据接口
        request={getArticleColumn}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={(
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          )}
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <Modal
        title="审核未通过"
        visible={visible}
        onOk={gooutArticleColumn}
        onCancel={() => {
          setVisible(false);
        }}
      >
        <label>审核未通过原因</label>
        <Input
          onChange={e => {
            setSubmitParams({
              ...submitParams,
              result: e.target.value,
            });
          }}
        />
      </Modal>
      <ModalForm
        title="添加专栏"
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async value => {
          addColumn(value.column);
          const success = await handleAdd(value as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        文章专栏
        <ProFormText
          rules={[
            {
              required: true,
              message: '规则名称为必填项',
            },
          ]}
          width="md"
          name="column"
        />
        {/* <ProFormTextArea width="md" name="desc" /> */}
      </ModalForm>
      <UpdateForm
        onSubmit={async value => {
          const success = await handleUpdate(value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
